﻿using ERP.RBAC;
using ERP.RBAC.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ERP.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly IMenuServices _menuServices;

        public HomeController(IMenuServices menuServices)
        {
            _menuServices = menuServices;
        }
        public async Task<IActionResult> Index()
        {
            var allMenus = await _menuServices.ShowMenu();


            // 构建菜单树
            var rootMenus = allMenus.Where(m => m.ParentId == null).ToList();

            foreach (var rootMenu in rootMenus)
            {
                rootMenu.Children = GetChildMenus(allMenus, rootMenu.Id);
            }

            return View(rootMenus);
        }

        public IActionResult Login()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction(nameof(Index));
            }
            return View();
        }

        public IActionResult Welcome()
        {
            return View();
        }

        private List<MenuDto> GetChildMenus(List<MenuDto> allMenus, int parentId)
        {
            var childMenus = allMenus.Where(m => m.ParentId == parentId).ToList();

            foreach (var childMenu in childMenus)
            {
                childMenu.Children = GetChildMenus(allMenus, childMenu.Id);
            }
            return childMenus;
        }
    }
}
